/*
 * Dispatcher.java
 *
 * Created on 10. duben 2008, 18:01
 */

package webstraming.ctrl;

import webstraming.beans.User;
import webstraming.dao.DbConnection;
import java.io.*;
import java.net.*;
import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

/**
 * Controller aplikace
 *
 * @author Tomas Kadlec
 * @version
 */
public class Dispatcher extends HttpServlet {
    
    /**
     * inicializace servletu - zajisti inicializaci datoveho zdroje
     */
    public void init() {
        // nastavi jmeno aplikace
        getServletContext().setAttribute("applicationName", "Y36TW2 - cvičení 7 - Kasino");
        // nastavi datovy zdroj
        DbConnection.setDataSource();
    }
    
    /** Zpracuje pozadavky zaslane metodou HTTP GET nebo POST
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        
        // ocekavany smer
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/score/casino");
        
        // ziskame session
        HttpSession httpSession = request.getSession();
        // prihalseni je nutne
        if (httpSession.getAttribute("user") == null) {
            rd = getServletContext().getRequestDispatcher("/score/login");
            
        }
        // odlhlaseni
        else if (request.getParameter("logout") != null) {
            httpSession.invalidate();
            rd = getServletContext().getRequestDispatcher("/score/logout.jsp");
        }
        rd.forward(request, response);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
